<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>个人购物车</title>
    <link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .nav_top {
            background-color: #f5f5f5;
        }

        #page-content .single-page {
            margin-top: 50px;
        }

        a {
            color: #000000;
        }

        a:hover, a:focus {
            color: #000000;
            text-decoration: none;
        }
    </style>
</head>
<body>
<div class="container-fluid nav_top">
    <div class="navbar-header">
        <a class="navbar-brand" th:href="@{/}">淘淘商城</a>
    </div>
    <div>
        <ul class="nav navbar-nav navbar-right">
            <li class="active" th:if="${session.user}==null"><a th:href="@{/login}">亲，请登录</a></li>
            <li class="dropdown" th:unless="${session.user}==null">
                <a class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true"
                   aria-expanded="false" href="#">
                    <span th:text="'欢迎您:' + ${session.user.username} + '!'"></span><span class="caret"></span></a>
                <ul class="dropdown-menu">
                    <li><a th:href="@{/user/logout}">退出</a></li>
                </ul>
            </li>
            <li>
                <a th:href="@{/user/cartList}">购物车</a>
            </li>
            <li>
                <a th:href="@{/user/order}">我的订单</a>
            </li>
        </ul>
    </div>
</div>
<div id="page-content">
    <div class="container single-page">
        <div class="row">
            <div class="col-lg-12">
                <a th:href="@{/user/cartList}">我的购物车</a>
                <hr/>
            </div>
        </div>
        <div class="row">
            <p><input type="checkbox" class="allCheck"/>全选</p>
        </div>
        <div class="row" th:if="${cartList.isEmpty()}">
            <div class="text-center"><span>亲，您的购物车中还没有商品，快去商城添加商品吧</span></div>
        </div>
        <div class="row" th:each="product:${cartList}">
            <a th:href="@{/user/cart/delete/{id}(id=${product.id})}">
                <button class="btn btn-warning" style="float: right;margin: 5px 5px 0 0; ">删除</button>
            </a>
            <div class="product">
                <div class="col-xs-5 col-sm-2 text-left">
                    <div class="image">
                        <input type="checkbox" class="check" th:value="${product.id}"
                               style="margin-left:-20px; margin-right:10px;"/>
                        <input type="hidden" th:value="${product.num}">
                        <img th:src="@{${product.imageUrl}}" style="width: 150px; height: 150px" class="img-rounded"/>
                    </div>
                </div>
                <div class="col-xs-7  col-sm-6">
                    <div class="caption">
                        <div class="name">
                            <a th:href="@{/product/{id}(id=${product.id})}" th:text="${product.name}">华为畅享10 6GB+64GB
                                全网通版（幻夜黑）</a><br/>
                        </div>
                    </div>
                </div>
                <div class="col-xs-12 col-sm-3 text-right ">
                    <p>¥<span th:text="${product.nowPrice}">1399.00</span></p>
                    <a th:href="@{/user/{userId}/add/{productId}/cart/-1(productId=${product.id},userId=${session.user.id})}">
                        <input type="button" value="-" class="btn btn-default"/></a>
                    <input type="text" style="width:40px; height:30px;" th:value="${product.num}" readonly="readonly"
                           class="btn btn-default product_num"/>
                    <a th:href="@{/user/{userId}/add/{productId}/cart/1(productId=${product.id},userId=${session.user.id})}">
                        <input type="button" value="+" class="btn btn-default"/></a>
                </div>
                <hr class="col-xs-12" style="padding: 0"/>
            </div>
        </div>
        <div class="row">
            <div class="col-xs-12 text-right">
                <button class="btn btn-warning btn-lg" th:if="${!cartList.isEmpty()}" id="deleteCart">清理商品</button>
                <button class="btn btn-danger btn-lg" th:if="${!cartList.isEmpty()}" id="buy">立即购买</button>
            </div>
        </div>
    </div>
</div>

</body>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
    $(document).ready(function () {
        let cartList = [];

        $('.allCheck').click(function () {
            if ($('.allCheck').is(":checked")) {
                $(".check").prop("checked", true);
                $(".check").each(function () {
                    let productId = $(this).val();
                    let num = $(this).next().val();
                    let product = {productId: productId, num: num}
                    cartList.push(product)
                })
            } else {
                $(".check").prop("checked", false);
                cartList = [];
            }
        })

        $('.check').click(function () {
            let productId = $(this).val();
            let num = $(this).next().val();
            let product = {productId: productId, num: num}
            if ($(this).is(":checked")) {
                cartList.push(product)
            } else {
                for (let i = 0; i < cartList.length; i++) {
                    if (cartList[i].productId === productId) {
                        cartList.splice(i, 1);
                    }
                }
            }
        })

        $(".check").click(function () {
            if ($(".check[class='check']:checked").length == $(".check[class='check']").length) {
                $(".allCheck").prop("checked", true);
            } else {
                $(".allCheck").prop("checked", false)
            }
        })

        $('#deleteCart').click(function () {
            if (cartList.length == 0) {
                alert("您还未选择商品")
                return;
            }
            $.ajax({
                url: 'http://localhost:8081/user/delete/cart',
                method: 'post',
                contentType: 'application/json;charset=utf-8',
                data: JSON.stringify(cartList),
                success: function (res) {
                    console.log(res);
                    if (res.code == 200) {
                        alert("删除成功！");
                        window.location.reload();
                    } else {
                        alert("删除失败！")
                        window.location.reload()
                    }
                },
                complete: function (xhr, status) {
                    //拦截器拦截没有权限跳转
                    // 通过xhr取得响应头
                    var REDIRECT = xhr.getResponseHeader("REDIRECT");
                    //如果响应头中包含 REDIRECT 则说明是拦截器返回的
                    if (REDIRECT == "REDIRECT") {
                        document.location.href = xhr.getResponseHeader("CONTENTPATH");
                    }
                }

            })

        })


        $('#buy').click(function () {
            if (cartList.length == 0) {
                alert("您还未选择商品")
                return;
            }
            $.ajax({
                url: 'http://localhost:8081/user/order/buy/cart',
                method: 'post',
                contentType: 'application/json;charset=utf-8',
                data: JSON.stringify(cartList),
                success: function (res) {
                    console.log(res);
                    if (res.code == 200) {
                        alert("下单成功！请15分钟之内完成支付");
                        window.location.href = "http://localhost:8081/user/order/details/" + res.data;
                    } else {
                        alert("下单失败！")
                        window.location.reload()
                    }
                },
                complete: function (xhr, status) {
                    //拦截器拦截没有权限跳转
                    // 通过xhr取得响应头
                    var REDIRECT = xhr.getResponseHeader("REDIRECT");
                    //如果响应头中包含 REDIRECT 则说明是拦截器返回的
                    if (REDIRECT == "REDIRECT") {
                        document.location.href = xhr.getResponseHeader("CONTENTPATH");
                    }
                }

            })
        })

    })
</script>
</html>